package org.zachary.creditbusiness.commodityandhouse.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zachary.creditbusiness.commodityandhouse.entity.Commodity;
import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityMapper;
import org.zachary.creditbusiness.commodityandhouse.service.CommodityService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityOrderMapper;
import org.zachary.creditbusiness.commodityandhouse.dto.CommodityWithPurchaseCount;
import org.zachary.creditbusiness.commodityandhouse.dto.CommodityWithPurchaseCount;
import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityOrderMapper;


import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private CommodityOrderMapper commodityOrderMapper;
    @Override
    public Commodity getCommodityById(Integer id) {
        return commodityMapper.selectById(id);
    }

    @Override
    public List<Commodity> getAllCommodities() {
        return commodityMapper.selectList(null);
    }

    @Override
    public Commodity createCommodity(Commodity commodity) {
        commodityMapper.insert(commodity);
        return commodity;
    }

    @Override
    public Commodity updateCommodity(Commodity commodity) {
        commodityMapper.updateById(commodity);
        return commodity;
    }

    @Override
    public void deleteCommodity(Integer id) {
        commodityMapper.deleteById(id);
    }

    @Override
    public Page<Commodity> getCommodities(int page, int size) {
        Page<Commodity> pageObj = new Page<>(page, size);
        return commodityMapper.selectPage(pageObj, null);
    }

    @Override
    public Page<Commodity> searchByName(String name, int page, int size) {
        Page<Commodity> pageObj = new Page<>(page, size);
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<Commodity>().like("name", name);
        return commodityMapper.selectPage(pageObj, queryWrapper);
    }

    @Override
    public List<Commodity> searchByName(String name) {
        return commodityMapper.selectList(new QueryWrapper<Commodity>().like("name", name));
    }

    @Override
    public Page<Commodity> filterByCategory(String category, int page, int size) {
        Page<Commodity> pageObj = new Page<>(page, size);
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<Commodity>().eq("category", category);
        return commodityMapper.selectPage(pageObj, queryWrapper);
    }

    @Override
    public List<Commodity> filterByCategory(String category) {
        return commodityMapper.selectList(new QueryWrapper<Commodity>().eq("category", category));
    }

    @Override
    public Page<Commodity> filterByPriceRange(Double minPrice, Double maxPrice, int page, int size) {
        Page<Commodity> pageObj = new Page<>(page, size);
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();
        if (minPrice != null) {
            queryWrapper.ge("price", minPrice);
        }
        if (maxPrice != null) {
            queryWrapper.le("price", maxPrice);
        }
        return commodityMapper.selectPage(pageObj, queryWrapper);
    }

    @Override
    public List<Commodity> filterByPriceRange(Double minPrice, Double maxPrice) {
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();
        if (minPrice != null) {
            queryWrapper.ge("price", minPrice);
        }
        if (maxPrice != null) {
            queryWrapper.le("price", maxPrice);
        }
        return commodityMapper.selectList(queryWrapper);
    }

    @Override
    public Page<Commodity> filterCommodities(String name, String category, Double minPrice, Double maxPrice, int page, int size) {
        Page<Commodity> pageObj = new Page<>(page, size);
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();

        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name.trim());
        }

        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq("category", category.trim());
        }

        if (minPrice != null) {
            queryWrapper.ge("price", minPrice);
        }

        if (maxPrice != null) {
            queryWrapper.le("price", maxPrice);
        }

        return commodityMapper.selectPage(pageObj, queryWrapper);
    }


    @Override
    public List<CommodityWithPurchaseCount> getTopThreePurchasedCommoditiesByUserId(Integer userId) {
        // 查询该用户的所有订单
        QueryWrapper<org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder> queryWrapper =
                new QueryWrapper<org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder>()
                        .eq("user_id", userId);
        List<org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder> orders =
                commodityOrderMapper.selectList(queryWrapper);

        // 统计每个商品ID的购买次数
        Map<Integer, Long> commodityCountMap = orders.stream()
                .collect(Collectors.groupingBy(
                        org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder::getCommodityId,
                        Collectors.counting()
                ));

        // 按购买次数降序排序，取前三个
        List<Map.Entry<Integer, Long>> topThree = commodityCountMap.entrySet().stream()
                .sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
                .limit(3)
                .collect(Collectors.toList());

        // 构建返回结果
        List<CommodityWithPurchaseCount> result = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : topThree) {
            Integer commodityId = entry.getKey();
            Long purchaseCount = entry.getValue();

            // 查询商品详情
            Commodity commodity = commodityMapper.selectById(commodityId);
            if (commodity != null) {
                CommodityWithPurchaseCount commodityWithCount =
                        new CommodityWithPurchaseCount(commodity, purchaseCount.intValue());
                result.add(commodityWithCount);
            }
        }

        return result;

    }










}

